import microApp from "@micro-zoe/micro-app";
import defaultConfig from "@/config/appUrlconfig";

/**
 * 向子应用发送主应用路由
 * @param router
 */
export const mainBaseAppRouter = (router: any) => {
  microApp.router.setBaseAppRouter(router);
};

/**
 * 卸载子应用
 * @param childrenApp
 * @param callBack
 */
export const unmountApp = (childrenApp: string, callBack?: () => void) => {
  microApp
    .unmountApp(childrenApp, { destroy: true })
    .then(() => {
      console.log("子应用" + childrenApp + "卸载成功");
      callBack && callBack();
    })
    .catch((err: any) => {
      console.log(err);
    });
};

/**
 * 重载子应用
 * @param childrenApp
 */
export const reloadApp = async (childrenApp: string) => {
  return await microApp.reload(childrenApp);
};

/**
 * 发送数据
 */
export const mainSendData = (appName: string, data: any, callback?: (data: any) => any) => {
  microApp.setData(appName, data, callback);
};
/**
 * 强制向子应用发送数据
 * @param appName
 * @param data
 * @param callback
 */
export const mainSendForceSetData = (appName: string, data: any, callback?: (data: any) => any) => {
  microApp.forceSetData(appName, data, callback);
};

/**
 * 接收数据
 */
export const mainReceiveData = (appName: string, dataListener: (data: object) => any, autoTrigger?: boolean) => {
  microApp.addDataListener(appName, dataListener, autoTrigger);
};
/**
 * 解绑数据监听
 * @param appName
 * @param dataListener
 */
export const mainRemoveDataListener = (appName: string, dataListener: (data: object) => any) => {
  microApp.removeDataListener(appName, dataListener);
};

/**
 * 预加载子应用
 */
export const preloadApp = () => {
  microApp.preFetch([
    { name: "form-design", url: defaultConfig.formDesign },
    { name: "crm", url: defaultConfig.crmUrl },
    { name: "project", url: defaultConfig.project },
    { name: "contract-template", url: defaultConfig.contractTemplate },
    { name: "sales-contract", url: defaultConfig.salesContract },
    { name: "factory", url: defaultConfig.factory },
    { name: "designer", url: defaultConfig.designer },
    { name: "business", url: defaultConfig.business },
    { name: "designForm", url: defaultConfig.designForm },
    { name: "finance", url: defaultConfig.finance },
    { name: "centralizedProcurement", url: defaultConfig.centralizedProcurement },
    { name: "commissionAgent", url: defaultConfig.commissionAgent }
  ]);
};

/**
 * 监听子应用路由变化
 */
export const mainListenRouterChange = () => {
  microApp.router.beforeEach({
    crm(to, from) {
      console.log("指定子应用的前置守卫 beforeEach ", to, from);
    }
  });
};
